package com.weituotian.moudle.member.controller;

import com.weituotian.core.controller.BaseController;
import com.weituotian.core.result.Result;
import com.weituotian.core.utils.FileUtil;
import com.weituotian.core.utils.PageInfo;
import com.weituotian.core.utils.ShiroUtil;
import com.weituotian.moudle.member.entity.Attachment;
import com.weituotian.moudle.member.entity.Video;
import com.weituotian.moudle.member.entity.vo.VideoListVo;
import com.weituotian.moudle.member.entity.vo.VideoVo;
import com.weituotian.moudle.member.service.IAttachmentService;
import com.weituotian.moudle.member.service.IPartitionService;
import com.weituotian.moudle.member.service.IVideoService;
import com.weituotian.system.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员上传视频
 * Created by ange on 2017/3/5.
 */
@Controller("memberVideoController")
@RequestMapping("${memberPath}/video")
public class VideoController extends BaseController {

    private final IVideoService videoService;

    private final IPartitionService partitionService;

    private final IAttachmentService attachmentService;


    @Autowired
    public VideoController(IVideoService videoService, IPartitionService partitionService, IAttachmentService attachmentService) {
        this.videoService = videoService;
        this.partitionService = partitionService;
        this.attachmentService = attachmentService;
    }

    @ModelAttribute
    public void initUrl(Model model) {
        String contextPath = this.getContextPath();
        model.addAttribute("cover_url", contextPath + memberPath + "/video/ajaxcover");
        model.addAttribute("video_url", contextPath + memberPath + "/video/ajaxvideo");

        model.addAttribute("edit_url", contextPath + memberPath + "/video/edit");
        model.addAttribute("delete_url", contextPath + memberPath + "/video/delete");

    }

    /**
     * 我的视频首页
     *
     * @return
     */
    @RequestMapping("/index")
    public String index(Integer page, Integer pagesize, Model model) {
        PageInfo<VideoListVo> pageInfo = new PageInfo<>(page, 10);

        //条件
        pageInfo.setCondition(getSearchMap());

        pageInfo.addSort("createTime", "desc");

        User user = ShiroUtil.getCurrentUser();
        videoService.findPageMemberVo(user.getId(), pageInfo);


        model.addAttribute("partitions", partitionService.findAll());

        model.addAttribute("pageName", "我的视频");

        model.addAttribute("pageinfo", pageInfo);

        return "member/video/index";
    }

    /**
     * 上传页面
     *
     * @return
     */
    @RequestMapping("/add")
    public String add(Model model) {
        Video video = new Video();


        model.addAttribute("partitions", partitionService.findAll());

        model.addAttribute("video", video);
        model.addAttribute("form_url", this.getContextPath() + memberPath + "/video/doadd");
        model.addAttribute("action", "add");

        model.addAttribute("pageName", "视频上传");

        return "member/video/upload";
    }


    @RequestMapping(value = "/doadd", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doadd(VideoVo videoVo) {
        try {
            videoService.addByDto(videoVo);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("提交成功");
    }

    /**
     * 修改页面
     *
     * @return
     */
    @RequestMapping("/edit")
    public String edit(Integer id, Model model) {

        Video video = videoService.findOneFetch(id);

        model.addAttribute("partitions", partitionService.findAll());

        model.addAttribute("video", video);
        model.addAttribute("form_url", this.getContextPath() + memberPath + "/video/doedit");
        model.addAttribute("action", "edit");

        model.addAttribute("pageName", "编辑视频");

        return "member/video/upload";
    }

    @RequestMapping(value = "/doedit", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doedit(VideoVo videoVo, Integer id) {
        try {
            videoService.updateByDto(videoVo, id);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("提交成功");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return
     */
    @RequestMapping(value = "/delete", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids[]") Integer[] ids) {
        try {
            videoService.deleteByIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("删除成功!");
    }

    /**
     * ajax上传封面
     *
     * @return
     */
    @RequestMapping(value = "/ajaxcover", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object ajaxCover(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        System.out.println("开始");
        String path = request.getSession().getServletContext().getRealPath(coverPath);//在磁盘上的绝对路径
        System.out.println(path);

        //前台canva传来的jpeg格式的图片
        String newFileName = FileUtil.generateNewFileName(file.getOriginalFilename(), "jpeg");

        File targetFile = new File(path, newFileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        //保存
        try {

            /*OutputStream out = new FileOutputStream(targetFile);
            InputStream in = file.getInputStream();
            int length;
            byte[] buf = new byte[1024];
            System.out.println("获取上传文件的总共的容量：" + file.getSize());
            // in.read(buf) 每次读到的数据存放在   buf 数组中
            while ((length = in.read(buf)) != -1) {
                //在   buf 数组中 取出数据 写到 （输出流）磁盘上
                out.write(buf, 0, length);
            }
            in.close();
            out.close();*/

            file.transferTo(targetFile);

            attachmentService.addTemp(file, targetFile);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError("服务器保存文件失败");
        }

        String fileUrl = request.getContextPath() + coverPath + "/" + newFileName;

        Result result = renderSuccess("");

        Map<String, String> urlMap = new HashMap<>();
        urlMap.put("url", fileUrl);
        urlMap.put("filename", newFileName);

        result.setObj(urlMap);
        return result;
    }

    /**
     * ajax上传视频
     *
     * @return
     */
    @RequestMapping(value = "/ajaxvideo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object ajaxVideo(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        System.out.println("开始");
        String path = request.getSession().getServletContext().getRealPath(videoPath);//在磁盘上的绝对路径
        System.out.println(path);

        //前台canva传来的jpeg格式的图片
        String newFileName = FileUtil.generateNewFileName(file.getOriginalFilename(), "mp4");
        File targetFile = new File(path, newFileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        Result result = new Result();

        //保存
        try {
            file.transferTo(targetFile);

            //视频附件
            Attachment attachment = attachmentService.addTemp(file, targetFile);

            result.setSuccess(true);
            result.setObj(attachment.getId());
            result.setMsg("视频上传成功");

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("服务器保存文件失败");
        }

        return result;
    }
}
